<?php


namespace App\Command\Changedata;

use App\Web\Model\CaseModel;
use EchoPHP\Console\Command;
use EchoPHP\Facades\Log;

class InitCaseResume extends Command {
    private $insertLength = 50;

    protected $signature = "changedata:initCaseResume";
    protected $description = '初始化caseresume分库操作。执行步骤：从数据库导出数据为csv(select resumeid,caseid,creator from CaseResume_bak into outfile \'/tmp/caseresume.csv\' fields terminated by \',\' lines terminated by \'\n\';)，整理数据并执行批量加入职位操作.';

    public function handle() {

        $resumeIdWithCaseId = [];

        $dataPath = ROOT_PATH . '/caseresume.csv';
        $fileHandle = fopen($dataPath, 'r');
        while ($row = fgets($fileHandle)) {
            $info = explode(',', $row);
            $itemResumeId = intval($info[0]);
            $itemCaseId = intval($info[1]);
            $itemOprId = intval($info[2]);

            if (!in_array($itemResumeId, $resumeIdWithCaseId[$itemCaseId][$itemOprId])) {
                $resumeIdWithCaseId[$itemCaseId][$itemOprId][] = $itemResumeId;
            }
        }

        $caseModel = new CaseModel();
        foreach ($resumeIdWithCaseId as $caseId => $item) {
            foreach ($item as $creator => $resumeIds) {
                while ($tmpResumeIds = array_splice($resumeIds, 0, $this->insertLength)) {
                    $result = $caseModel->addToCase($creator, $caseId, $tmpResumeIds);//每次插入50条
                    if ($result['status'] != 0) {
                        $message = '批处理简历数组初始化出现异常:[' . $result['message'] . ']';
                        $context = [
                            'caseid' => $caseId,
                            'creator' => $creator,
                            'resumeids' => $tmpResumeIds
                        ];
                        Log::error($message, $context);
                        $this->output->error($message);
                    }
                }
            }
            $this->output->success('caseid:[' . $caseId . ']处理完成');
        }
    }
}